import { login, logout, getInfo, smsLogin, record } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'

const user = {
    state: {
        token: getToken(),
        name: '',
        avatar: '',
        roles: [],
        permissions: [],
        defaultIndex: ''
    },

    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token
        },
        SET_NAME: (state, name) => {
            state.name = name
        },
        SET_AVATAR: (state, avatar) => {
            state.avatar = avatar
        },
        SET_ROLES: (state, roles) => {
            state.roles = roles
        },
        SET_PERMISSIONS: (state, permissions) => {
            state.permissions = permissions
        },
        SET_DEFAULT_INDEX: (state, defaultIndex) => {
            state.defaultIndex = defaultIndex
        }
    },

    actions: {

        // 短信登录
        smsLogin({ commit }, smsInfo) {
            return new Promise((resolve, reject) => {
                smsLogin(smsInfo).then(res => {
                    setToken(res.data.token)
                    commit('SET_TOKEN', res.data.token)
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 登录
        Login({ commit }, userInfo) {
            const username = userInfo.username.trim()
            const password = userInfo.password
            const code = userInfo.code
            const uuid = userInfo.uuid
            return new Promise((resolve, reject) => {
                login(username, password, code, uuid).then(res => {
                    setToken(res.data.accessToken)
                    commit('SET_TOKEN', res.data.accessToken)
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 获取用户信息
        GetInfo({ commit }) {
            return new Promise((resolve, reject) => {
                getInfo().then(res => {

                    console.log(res)

                    const projectList = res.data.projectList

                    const user = res.data.user

                    // const projectId = user.projectId

                    const avatar = user.avatar == '' ? require('@/assets/images/profile.jpg') : process.env.VUE_APP_BASE_API + user.avatar
                    // 验证返回的roles是否是一个非空数组
                    if (res.data.roles && res.data.roles.length > 0) {
                        commit('SET_ROLES', res.data.roles)
                        commit('SET_PERMISSIONS', res.data.permissions)
                    } else {
                        commit('SET_ROLES', ['ROLE_DEFAULT'])
                        commit('SET_PERMISSIONS', res.data.permissions)
                    }
                    commit('SET_NAME', user.userName)

                    // console.log('上次项目', projectId)

                    // commit('SET_PROJECT_ID', projectId)
                    // commit('SET_DEFAULT_INDEX', user.defaultIndex)

                    let arr = []
                    // for (let i = 0, len = projectList.length; i < len; ++i) {
                    //
                    //   let item = projectList[i]
                    //
                    //   let temp = { 'value': 0, 'label': '' }
                    //   temp['value'] = item.projectId
                    //   temp['label'] = item.projectName
                    //   arr.push(temp)
                    //
                    //   // this.options.push(temp)
                    //   // this.projectDataList.push(item)
                    //
                    //   if (projectId == null) {
                    //
                    //     if (i === 0) {
                    //
                    //       let obj = { 'projectId': item.projectId }
                    //       record(obj).then(response => {
                    //       })
                    //
                    //       // this.$store.dispatch('setProjectId', item.projectId)
                    //       // console.log("设置projectId")
                    //
                    //       commit('SET_PROJECT_ID', item.projectId)
                    //       commit('SET_DEFAULT_INDEX', item.defaultIndex)
                    //
                    //       // this.$router.push({
                    //       //   path: '/black',
                    //       //   query: {
                    //       //     willPath: path
                    //       //   }
                    //       // })
                    //       //
                    //       // // 用电项目需要注释，农业需要打开
                    //       // if ('/index' === path) {
                    //       //   this.$router.push({ path: this.redirect || '/control/loop' }).catch(() => {
                    //       //   })
                    //       // }
                    //     }
                    //   }
                    // }

                    commit('SET_PROJECT_LIST', arr)
                    // commit('SET_PROJECT_DATA_LIST', projectList)
                    commit('SET_AVATAR', avatar)

                    resolve(res)
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 退出系统
        LogOut({ commit, state }) {
            return new Promise((resolve, reject) => {
                logout(state.token).then(() => {
                    commit('SET_TOKEN', '')
                    commit('SET_ROLES', [])
                    commit('SET_PERMISSIONS', [])
                    removeToken()
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },

        SetDefaultIndex({ commit }, defaultIndex) {
            commit('SET_DEFAULT_INDEX', defaultIndex)
        },

        // 前端 登出
        FedLogOut({ commit }) {
            return new Promise(resolve => {
                commit('SET_TOKEN', '')
                removeToken()
                resolve()
            })
        }
    }
}

export default user
